using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;
using MESTranslateToPLC.Manager;
using MESTranslateToPLC.Schema.Request;
using MESTranslateToPLC.Schema.Response;
using MESTranslateToPLC.Service;
using MESTranslateToPLC.Service.BackgroudService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NModbus.Device;
using NModbus.IO;

namespace MESTranslateToPLC.Controllers;

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    private readonly ModbusService? _modbusService;
    private readonly ModbusDeviceManager _modbusDeviceManager;

    public TestController(ModbusDeviceManager modbusDeviceManager)
    {
        _modbusDeviceManager = modbusDeviceManager;
        _modbusService = _modbusDeviceManager.GetDefaultDeviceService();
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] ModBusSetCoinsRequest request)
    {
        if (_modbusService is not null)
        {
            try
            {
                if (_modbusService.IsConnected)
                {
                    //todo: 翻译json请求数据以modbus传递给下位机

                    await _modbusService.WriteMultipleCoilsAsync(request.SlaveAddress, request.Address,
                        request.Values.ToArray());
                    return NoContent();
                }
            }
            catch (NModbus.SlaveException e)
            {
                Console.WriteLine(e);
                return BadRequest(new ErrorResponse
                {
                    errorCode = e.SlaveExceptionCode,
                    errorMessage = $"SlaveAddress: {request.SlaveAddress}不存在或传递的其他参数有问题",
                    errorDetails = e.Message
                });
            }
        }

        return NotFound(new { error = "设备未连接" });
    }

    [HttpGet]
    public async Task<IActionResult> Get([FromQuery] ModBusGetCoinsRequest request)
    {
        if (_modbusService is not null)
        {
            try
            {
                if (_modbusService.IsConnected)
                {
                    var result = await _modbusService.ReadCoilsAsync(request.SlaveAddress, request.Address,
                        request.Count);
                    return Ok(new ModBusGetCoinsResponse
                    {
                        Address = request.Address,
                        Count = request.Count,
                        SlaveAddress = request.SlaveAddress,
                        Values = result.ToList()
                    });
                }
            }
            catch (NModbus.SlaveException e)
            {
                Console.WriteLine(e);
                return BadRequest(new ErrorResponse
                {
                    errorCode = e.SlaveExceptionCode,
                    errorMessage = $"SlaveAddress: {request.SlaveAddress}不存在或传递的其他参数有问题",
                    errorDetails = e.Message
                });
            }
        }

        return NotFound(new { error = "设备未连接" });
    }

    [HttpOptions]
    public IActionResult Options()
    {
        return Ok();
    }
}